package com.mzj.eagle.jobs.config.es;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EsClusterConfig {

	private static final Logger LOG = LoggerFactory.getLogger(EsClusterConfig.class);

	@Value("${elasticsearch.rest.java.url}")
	private String elsUrl;

	@Bean(name = "esHighRestClient")
	public RestHighLevelClient highClient() {

		LOG.info("------> elasticsearch url {}", elsUrl);

		String[] urlList = elsUrl.split("\\,");
		List<HttpHost> list = new ArrayList<HttpHost>();
		for (String urlPort : urlList) {
			if (StringUtils.isEmpty(urlPort)) {
				continue;
			}
			String url = urlPort.split("\\:")[0];
			String port = urlPort.split("\\:")[1];
			list.add(new HttpHost(url, Integer.valueOf(port), "http"));
		}
		HttpHost[] arr = new HttpHost[list.size()];
		arr = list.toArray(arr);
		RestClientBuilder builder = RestClient.builder(arr)
				.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
					@Override
					public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
						requestConfigBuilder.setConnectTimeout(5000);
						requestConfigBuilder.setSocketTimeout(40000);
						requestConfigBuilder.setConnectionRequestTimeout(1000);
						return requestConfigBuilder;
					}

				}).setMaxRetryTimeoutMillis(20 * 60 * 1000);

		return new RestHighLevelClient(builder);
	}
}
